"""
技术分析智能体

负责股票技术分析，包括技术指标计算、趋势分析、图表模式识别等
"""

from agno.agent import Agent
from ..utils.model_factory import create_model
from typing import Dict, Any, Optional, List
import logging
from datetime import datetime, timedelta
from ..tools.technical_analysis import TechnicalAnalysisTools
from ..tools.akshare_client import AkShareClient
from ..models.market_data import StockPrice
from ..models.analysis_results import TechnicalAnalysis, AgentExecutionLog

logger = logging.getLogger(__name__)


class TechnicalAnalystAgent:
    """技术分析智能体类"""
    
    def __init__(self, model_id: str = "deepseek-chat"):
        """
        初始化技术分析智能体
        
        Args:
            model_id: LLM模型ID
        """
        self.technical_tools = TechnicalAnalysisTools()
        self.akshare_client = AkShareClient()
        
        # 定义技术分析工具
        def analyze_technical_indicators(agent: Agent, ticker: str) -> str:
            """
            分析技术指标
            
            Args:
                ticker: 股票代码
                
            Returns:
                str: 技术分析结果
            """
            try:
                logger.info(f"开始技术分析: {ticker}")
                
                # 从 Workflow 的共享状态中获取收集的数据
                from ..models.market_data import TechnicalIndicators, StockPrice

                if "collected_data" not in agent.workflow_session_state:
                    print("taggggg")
                    return f"尚未找到收集的数据，请先运行市场数据收集智能体。"

                collected = agent.workflow_session_state["collected_data"]
                if ticker not in collected:
                    return f"未找到 {ticker} 的收集数据，请先收集该股票的数据。"

                summary = collected[ticker].get("summary", {})
                indicators_dict = summary.get("technical_indicators", {})
                price_data_list = summary.get("price_data", [])

                if not indicators_dict or not price_data_list:
                    return f"{ticker} 的收集数据不完整，请先确保已完成数据收集。"

                indicators = TechnicalIndicators(**indicators_dict)
                price_data = [StockPrice(**price_item) for price_item in price_data_list]

                # 进行综合技术分析
                analysis = self.technical_tools.comprehensive_technical_analysis(price_data, indicators)
                # 保存分析结果到状态
                if "technical_analysis" not in agent.workflow_session_state:
                    agent.workflow_session_state["technical_analysis"] = {}
                
                agent.workflow_session_state["technical_analysis"][ticker] = {
                    "analysis": analysis.model_dump(),
                    "indicators": indicators.model_dump(),
                    "analysis_time": datetime.now().isoformat(),
                    "data_points": len(price_data)
                }
                
                # 生成分析报告
                report = f"""技术分析报告 - {ticker}

**分析结论**
- 技术信号: {analysis.signal.upper()}
- 置信度: {analysis.confidence:.1%}
- 策略信号: {analysis.strategy_signals.upper()}
- 策略置信度: {analysis.strategy_confidence:.1%}

**关键技术指标**
- RSI: {indicators.rsi:.1f} {'(超买)' if indicators.rsi and indicators.rsi > 70 else '(超卖)' if indicators.rsi and indicators.rsi < 30 else '(正常)'}
- MACD: {indicators.macd:.4f} {analysis.reasoning.get('macd')}
- SMA5: {indicators.sma5:.2f} | SMA20: {indicators.sma20:.2f}
- EMA8: {indicators.ema8:.2f} | EMA21: {indicators.ema21:.2f} | EMA55: {indicators.ema55:.2f}

**详细分析**
{chr(10).join([f"- {key}: {value}" for key, value in analysis.reasoning.items()])}

**支撑阻力位**
- 支撑位: {analysis.support_resistance.get('support', 0):.2f}
- 阻力位: {analysis.support_resistance.get('resistance', 0):.2f}

**投资建议**
基于技术分析，当前技术分析为{analysis.signal}信号，策略分析为{analysis.strategy_signals}信号，建议{'买入' if analysis.strategy_signals == 'bullish' and analysis.signal == 'bullish' else '卖出' if analysis.strategy_signals == 'bearish' and analysis.signal == 'bearish' else '观望'}。
技术分析置信度为{analysis.confidence:.1%}，策略分析置信度为{analysis.strategy_confidence:.1%}，请结合基本面分析做出最终决策。

数据来源: {len(price_data)} 个交易日数据
分析时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"""
                
                logger.info(f"技术分析完成: {ticker}")
                return report
                
            except Exception as e:
                error_msg = f"技术分析失败: {str(e)}"
                logger.error(error_msg)
                return error_msg
        
        def get_technical_summary(agent: Agent) -> str:
            """
            获取技术分析摘要
            
            Returns:
                str: 技术分析摘要
            """
            if "technical_analysis" not in agent.workflow_session_state:
                return "尚未进行任何技术分析"
            
            analyses = agent.workflow_session_state["technical_analysis"]
            summary_lines = ["技术分析摘要:"]
            
            for ticker, data in analyses.items():
                analysis = data.get("analysis", {})
                signal = analysis.get("signal", "unknown")
                confidence = analysis.get("confidence", 0)
                analysis_time = data.get("analysis_time", "unknown")
                
                signal_emoji = "🟢" if signal == "bullish" else "🔴" if signal == "bearish" else "🟡"
                summary_lines.append(f"- {ticker}: {signal_emoji} {signal.upper()} (置信度: {confidence:.1%}) [{analysis_time}]")
            
            return "\n".join(summary_lines)
        
        def compare_technical_signals(agent: Agent, tickers: str) -> str:
            """
            比较多个股票的技术信号
            
            Args:
                tickers: 股票代码列表，用逗号分隔
                
            Returns:
                str: 技术信号比较结果
            """
            ticker_list = [t.strip() for t in tickers.split(",")]
            
            if "technical_analysis" not in agent.workflow_session_state:
                return "尚未进行任何技术分析，请先分析相关股票"
            
            analyses = agent.workflow_session_state["technical_analysis"]
            comparison_lines = ["技术信号比较:"]
            
            bullish_stocks = []
            bearish_stocks = []
            neutral_stocks = []
            
            for ticker in ticker_list:
                if ticker in analyses:
                    analysis = analyses[ticker]["analysis"]
                    signal = analysis.get("signal", "neutral")
                    confidence = analysis.get("confidence", 0)
                    
                    if signal == "bullish":
                        bullish_stocks.append(f"{ticker} ({confidence:.1%})")
                    elif signal == "bearish":
                        bearish_stocks.append(f"{ticker} ({confidence:.1%})")
                    else:
                        neutral_stocks.append(f"{ticker} ({confidence:.1%})")
                else:
                    neutral_stocks.append(f"{ticker} (未分析)")
            
            if bullish_stocks:
                comparison_lines.append(f"🟢 看涨信号: {', '.join(bullish_stocks)}")
            if bearish_stocks:
                comparison_lines.append(f"🔴 看跌信号: {', '.join(bearish_stocks)}")
            if neutral_stocks:
                comparison_lines.append(f"🟡 中性信号: {', '.join(neutral_stocks)}")
            
            return "\n".join(comparison_lines)
        
        # 创建Agno智能体
        self.agent = Agent(
            name="Technical Analyst Agent",
            role="股票技术分析专家",
            model=create_model(model_id),
            tools=[analyze_technical_indicators, get_technical_summary, compare_technical_signals],
            instructions="""你是一个专业的技术分析师，专注于股票技术分析，具备以下能力：

1. **技术指标分析**
   - 计算和解读各种技术指标（RSI、MACD、移动平均线等）
   - 识别超买超卖信号
   - 分析价格动量和趋势强度

2. **图表模式识别**
   - 识别支撑阻力位
   - 分析价格趋势和反转信号
   - 评估成交量与价格的关系

3. **综合技术评估**
   - 整合多个技术指标给出综合判断
   - 评估技术信号的可靠性和置信度
   - 提供明确的买卖建议

4. **风险提示**
   - 识别技术分析的局限性
   - 提醒关注基本面因素
   - 建议合理的止损和止盈位

当前技术分析状态: {technical_analysis}

请基于技术分析方法，为用户提供专业的股票技术分析服务。""",
            add_state_in_messages=True,
            show_tool_calls=True,
            markdown=True
        )
        
        logger.info("技术分析智能体初始化完成")
    
    def run(self, message: str, **kwargs) -> str:
        """
        运行智能体
        
        Args:
            message: 用户消息
            **kwargs: 其他参数
            
        Returns:
            str: 智能体响应
        """
        try:
            start_time = datetime.now()
            
            # 运行智能体
            response = self.agent.run(message, **kwargs)
            
            end_time = datetime.now()
            duration = (end_time - start_time).total_seconds()
            
            logger.info(f"技术分析智能体执行完成，耗时: {duration:.2f}秒")
            
            # 正确处理RunResponse对象
            if response:
                if hasattr(response, 'content'):
                    return str(response.content) if response.content else "执行失败，未收到响应内容"
                else:
                    return str(response) if response else "执行失败，响应为空"
            else:
                return "执行失败，未收到响应"
            
        except Exception as e:
            error_msg = f"技术分析智能体执行失败: {str(e)}"
            logger.error(error_msg)
            return error_msg
    
    def print_response(self, message: str, stream: bool = True, **kwargs):
        """
        打印智能体响应
        
        Args:
            message: 用户消息
            stream: 是否流式输出
            **kwargs: 其他参数
        """
        self.agent.print_response(message, stream=stream, **kwargs)

    def get_analysis_result(self, ticker: str) -> Optional[Dict[str, Any]]:
        """
        获取技术分析结果
        
        Args:
            ticker: 股票代码
            
        Returns:
            Optional[Dict[str, Any]]: 分析结果，如果不存在则返回None
        """
        analyses = self.agent.workflow_session_state.get("technical_analysis", {})
        return analyses.get(ticker)
